<?php

namespace app\common\model\mall\goods;

use think\Model;
use think\Db;

class Goods extends Model
{
    // 表名
    protected $name = 'mall_goods_goods';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = "int";

    // 定义时间戳字段名
    protected $createTime = "createtime";
    protected $updateTime = "updatetime";
    
    // 追加属性
    protected $append = [
        'url',
        'fullurl',
        'goodstype_text',
        'freighttype_text',
        'goodscat_ids_text',
        'status_text',
    ];

    protected static function init()
    {
        $config = get_addon_config('mall');
        self::afterInsert(function ($row) use ($config) {
            //新增积分汇总记录
            \app\common\model\mall\goods\Raty::create(["goods_id"=>$row->id]);
        });
        self::afterDelete(function ($row) use ($config) {
            //删除积分汇总记录
            \app\common\model\mall\goods\Raty::destroy($row->id);
        });
    }

    public function getGoodstypeList()
    {
        return ['0' => __('Goodstype 0'),'1' => __('Goodstype 1')];
    }

    public function getFreighttypeList()
    {
        return ['0' => __('Freighttype 0'),'1' => __('Freighttype 1'),'2' => __('Freighttype 2'),'3' => __('Freighttype 3'),'4' => __('Freighttype 4')];
    }

    public function getStatusList()
    {
        return ['sale' => __('Status sale'),'audit' => __('Status audit'),'store' => __('Status store'),'illegal' => __('Status illegal'),'warn' => __('Status warn')];
    }

    public function getGoodstypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['goodstype']) ? $data['goodstype'] : '');
        $list = $this->getGoodstypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getFreighttypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['freighttype']) ? $data['freighttype'] : '');
        $list = $this->getFreighttypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getGoodscatIdsTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['goodscat_ids']) ? $data['goodscat_ids'] : '');
        $names = model("\app\common\model\mall\goods\Cat")->where("id","in",$value)->column("simplename");
        return empty($names) ? "" : implode("\\", $names);
    }

    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getUrlAttr($value, $data)
    {
        return addon_url('mall/goods/detail', [':ids' => $data['id']]);
    }

    public function getFullUrlAttr($value, $data)
    {
        return addon_url('mall/goods/index', [':id' => $data['id']], true, true);
    }

    public function getImageAttr($value, $data)
    {
        $mallcdn = config("mall.mallcdn");
        if($mallcdn && !stristr($value,$mallcdn))
            return $mallcdn ? $mallcdn.$value : cdnurl($value);
        else
            return cdnurl($value);
    }

    public function getGoodsimgAttr($value, $data)
    {
        $mallcdn = config("mall.mallcdn");
        if($mallcdn && !stristr($value,$mallcdn))
            return $mallcdn ? $mallcdn.$value : cdnurl($value);
        else
            return cdnurl($value);
    }

    public function getGalleryAttr($value, $data){
        //value中没有添加mallcdn
        if($value){
            if(is_string($value)) $value = explode(",", $value);
            foreach ($value as $k=>$v){
                if(config("mall.mallcdn") && !stristr($v, config("mall.mallcdn"))) {
                    $value[$k] = config("mall.mallcdn").$v ;
                }else $value[$k] = cdnurl($v);

            }
                $value = implode(',',$value);
        }
        return $value;
    }

    public function getGoodsdescAttr($value, $data)
    {
        $rule = '/<img src="\/(upload.*?)"/';
        $images = [];
        preg_match_all($rule, $value, $images);
        foreach($images[0] as $k=>$v){
            $value = str_replace($v, "<img src=\"".config('mall.mallcdn')."/".$images[1][$k]."\"", $value);
        }
        return $value;
    }

    /**
     * 获取店铺商品列表
     */
    public function shopGoods($shop_id){
        $msort = input("param.msort/d");
        $mdesc = input("param.mdesc/d");
        $order = array('g.saleTime'=>'desc');
        $orderFile = array('1'=>'g.isHot','2'=>'g.saleNum','3'=>'g.shopPrice','4'=>'g.shopPrice','5'=>'(gs.totalraty/gs.users)','6'=>'g.saleTime');
        $orderSort = array('0'=>'asc','1'=>'desc');
        if($msort>0){
            $order = array($orderFile[$msort]=>$orderSort[$mdesc]);
        }
        $goodsname = input("param.goodsname");//搜索店鋪名
        $words = $where = $where2 = $where3 = $where4 = [];
        if($goodsname!=""){
            $words = explode(" ",$goodsname);
        }
        if(!empty($words)){
            $sarr = array();
            foreach ($words as $key => $word) {
                if($word!=""){
                    $sarr[] = "g.goodsname like '%$word%'";
                }
            }
            $where4 = implode(" or ", $sarr);
        }
        
        $sprice = input("param.sprice");//开始价格
        $eprice = input("param.eprice");//结束价格
        if($sprice!="")$where2 = "g.shopPrice >= ".(float)$sprice;
        if($eprice!="")$where3 = "g.shopPrice <= ".(float)$eprice;
        $ct1 = input("param.ct1/d");
        $ct2 = input("param.ct2/d");
        if($ct1>0&&$ct2>0)$where['shopcat_ids'] = $ct1.",".$ct2;
        elseif($ct1>0)$where['shopcat_ids'] = $ct1;
        $goods = model('\app\common\model\mall\goods\Goods')->alias('g')
        	->join('__MALL_GOODS_RATY__ gs','gs.goods_id = g.id','left')
        	->where(['g.shop_id'=>$shop_id,'g.goodsstatus'=>1,'g.status'=>'normal'])
        	->where($where)->where($where2)->where($where3)->where($where4)
        	->field('g.id,g.goodsname,g.goodsImg,g.shopPrice,g.marketPrice,g.saleNum,g.appraisenum,g.goodsStock,g.freighttype,gallery')
        	->order($order)
        	->paginate((input('pagesize/d')>0)?input('pagesize/d'):16);
        return  $goods;
    }

    /**
     * 检测商品主表的货号或者商品编号
     */
    public function checkExistGoodsKey($key,$val,$id = 0){
        if(!in_array($key,array('goodsSn','productNo')))throw new Exception("非法的查询字段");
        $conditon[$key] = $val;
        if($id>0)$conditon['id'] = ['<>',$id];
        $conditon['shop_id'] = (int)cookie('shop_id');
        $rs = $dbo = $this->where($conditon)->count();
        return ($rs==0)?false:true;
    }

    /**
     * 获取商品资料在前台展示
     */
    public function getBySale($goods_id){
        $key = input('key');
        $rs = $this->get($goods_id,'shop');
        if(!empty($rs)){
            // 浏览量
            $rs->setInc('visitnum',1);
            $rs['read'] = false;
            $rs['goodsdesc'] = htmlspecialchars_decode($rs['goodsdesc']);
            $rs['goodsdesc'] = str_replace('${DOMAIN}',config('site.cdnurl'),$rs['goodsdesc']);
            if($key!='') $rs['read'] = true;
            $rs['gallery'] = $rs['goodsimg'].",".$rs['gallery'];
            $rs = $rs->toArray();
            if($rs['specis']){
                //获取规格值
                $specs = Db::name('mall_goods_catspec')->alias('gc')
                    ->join('__MALL_GOODS_SPECITEM__ sit','gc.id=sit.spec_id','LEFT')
                    ->where(['sit.goods_id'=>$goods_id,'gc.showis'=>1])
                    ->field('gc.allowimgis,gc.specname,sit.spec_id,sit.itemId,sit.itemname,sit.itemimg')
                    ->order('gc.allowimgis desc,gc.weigh asc,gc.id asc')->select();
                foreach ($specs as $key =>$v){
                    $rs['spec'][$v['spec_id']]['name'] = $v['specname'];
                    $rs['spec'][$v['spec_id']]['list'][] = $v;
                }

                //获取销售规格
                $sales = Db::name('mall_goods_salespec')
                    ->field('id,defaultis,productno,specitem_ids,marketprice,specprice,specstock')
                    ->where('goods_id',$goods_id)->select();
                if(!empty($sales)){
                    foreach ($sales as $key =>$v){
                        $str = explode(':',$v['specitem_ids']);
                        sort($str);
                        unset($v['specitem_ids']);
                        $rs['saleSpec'][implode(':',$str)] = $v;
                        if($v['defaultis']==1)$rs['defaultSpecs'] = $v;
                    }
                }
            }
            //获取商品属性
            $rs['attrs'] = Db::name('mall_goods_catattr')->alias('a')
                ->join('__MALL_GOODS_GOODSATTR__ ga','a.id=ga.attr_id','inner')
                ->where(['a.showis'=>1,'goods_id'=>$goods_id])
                ->field('a.attrname,ga.attrval')
                ->order('weigh asc')->select();
            //获取商品评分
            $score = model('Raty','common\model\mall\goods')
                ->where('goods_id',$goods_id)->find();
            $rs['raty']['totalScore'] = $score['totalraty5'];

            //品牌名称
            $rs['brandName'] = Db::name('mall_goods_brand')
                ->where(['id'=>$rs['brand_id']])->value('name');
            //关注
            $f = model('\app\common\model\mall\user\Favorite');
            $rs['favShop'] = $f->checkFavorite($rs['shop_id'],2);
            $rs['favGood'] = $f->checkFavorite($goods_id,1);
        }
        $rs['gallery'] = explode(",", $rs['gallery']);
        return $rs;
    }

    /**
	 * 获取分类规格和分类属性
	 */
	public function getSpecAttrs($goodsType,$goodsCatId){
		$goodsCatIds = model('app\common\model\mall\goods\Cat')->getParentIds($goodsCatId);
        $goodsCatIds = implode(",",$goodsCatIds);
		$data = [];
		if($goodsType==0){
			$specs = Db::name('mall_goods_catspec')
				->where([''=>['EXP',Db::raw("INSTR('$goodsCatIds', goodsCatPath)")],'showis'=>1,'status'=>'normal'])
				->field('cat_id,catName,isAllowImg')
				->order('isAllowImg desc,weigh asc,cat_id asc')->select();
			$spec0 = null;
			$spec1 = [];
			foreach ($specs as $v){
				if($v['isAllowImg']==1){
					$spec0 = $v;
				}else{
					$spec1[] = $v;
				}
			}
			$data['spec0'] = $spec0;
			$data['spec1'] = $spec1;
		}
		$data['attrs'] = Db::name('mall_goods_catattr')->where([''=>['EXP',Db::raw("INSTR('$goodsCatIds', goodscat_ids)")],'showis'=>1,'status'=>'normal'])->field('id,attrName,attrType,attrVal')->order('weigh asc,id asc')->select();
	    return json(["data"=>$data,"status"=>1]);
	}


    /**
     * 建立与 Shop 表的关联模型（一对一）
     * @return \think\model\relation\BelongsTo
     */
    public function shop()
    {
        return $this->belongsTo('\app\common\model\mall\shop\Shop', 'shop_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function raty()
    {
        return $this->hasOne('\app\common\model\mall\goods\Raty', 'goods_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
